package itsm.isperp.framework.ldap;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.commons.lang3.StringUtils;

/**
 * 
 * Ldap上下文工具
 * 
 * @author lizx
 * @date 2014-9-7
 * @since 1.0
 * 
 */
public class LdapContextUtils {

	public static final String USER = "objectClass=user";// 用户
	public static final String UNIT = "objectClass=organizationalUnit";// 组织
	public static final String GROUP = "objectClass=group";// 用户组

	/**
	 * 获取Ldap上下文
	 * 
	 * @return
	 * @throws NamingException
	 */
	public static boolean checkLogin(final String host, final String port,
			final String username, final String password) {

		String url = new String("ldap://" + host + ":" + port);

		Hashtable<String, String> HashEnv = new Hashtable<String, String>();
		HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple");

		HashEnv.put(Context.SECURITY_PRINCIPAL, username);
		HashEnv.put(Context.SECURITY_CREDENTIALS, password);

		HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类

		HashEnv.put(Context.PROVIDER_URL, url);
		try {
			new InitialLdapContext(HashEnv, null);
			return true;
		} catch (Exception e) {

			return false;
		}
	}

	/**
	 * 获取Ldap上下文
	 * 
	 * @return
	 * @throws NamingException
	 */
	public static LdapContext getLdapContext(final String host,
			final String port, final String dc, final String username,
			final String password) throws NamingException {

		String url = new String("ldap://" + host + ":" + port);

		Hashtable<String, String> HashEnv = new Hashtable<String, String>();
		HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple");

		HashEnv.put(Context.SECURITY_PRINCIPAL, username);
		HashEnv.put(Context.SECURITY_CREDENTIALS, password);

		HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类

		HashEnv.put(Context.PROVIDER_URL, url);
		HashEnv.put("userAccountControl", "512");

		return new InitialLdapContext(HashEnv, null);

	}

	/**
	 * 获取域控制器DC
	 * 
	 * @return
	 */
	public static String getDomainController(final String dc) {
		String[] dcArr = dc.split("\\.");
		String sb = "DC=" + dcArr[0];
		for (int i = 1; i < dcArr.length; i++) {
			sb += ",DC=" + dcArr[i];
		}
		return sb;
	}

	/**
	 * 获取域控制器上组织结构搜索路径
	 * 
	 * @return
	 */
	public static String getDomainControllerOU(final String dc,
			final String searchOU) {
		String str = new StringBuilder(dc).toString();
		if (StringUtils.isNotEmpty(searchOU) && !"*".equals(searchOU)) {
			if (searchOU.contains(",")) {
				String[] o = searchOU.split(",");
				String re = "";
				for (String s : o) {
					re = "OU=" + s + "," + re;
				}

				str = re + str;
			} else {

				str = "OU=" + searchOU + "," + str;
			}
		}
		return str;

	}

}
